package com.example;

import com.example.Entity.Enum.QosEnum;
import com.example.config.MqttProperties;
import com.example.controller.EmqClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class EmqDemoApplication {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private MqttProperties mqttProperties;

    public static void main(String[] args) {
        SpringApplication.run(EmqDemoApplication.class, args);
    }
    @PostConstruct
    public void init(){
        emqClient.connect(mqttProperties.getUsername(),mqttProperties.getPassword());
        //订阅某一主题
//        emqClient.subscribe("testtopic/#", QosEnum.QOS_2);
        //开启一个新的线程向该主题发送消息
        new Thread(()->{
            while (true){
                emqClient.publish("testtopic/123","mqtt msg:"+
                        LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),QosEnum.QOS_2,false);
                System.out.println("发布成功");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
